<template>
  <div class="bills-container">
    <van-nav-bar title="账单列表" :fixed="true" />
    
    <div class="content" style="padding-top: 46px;">
      <van-search
        v-model="searchValue"
        placeholder="搜索账单"
        @search="onSearch"
      />
      
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-cell-group inset>
            <van-cell
              v-for="bill in bills"
              :key="bill.id"
              :title="bill.title"
              :label="`${bill.category} · ${formatDate(bill.date)}`"
              :value="`¥${bill.amount}`"
              :value-class="bill.amount > 0 ? 'amount-positive' : 'amount-negative'"
              is-link
              @click="viewBill(bill.id)"
            />
          </van-cell-group>
        </van-list>
      </van-pull-refresh>
      
      <div v-if="isAdmin" class="add-button">
        <van-button type="primary" icon="plus" round @click="showAddDialog = true" />
      </div>
    </div>
    
    <van-tabbar v-model="activeTab" fixed>
      <van-tabbar-item icon="orders-o" to="/bills">账单</van-tabbar-item>
      <van-tabbar-item icon="user-o" @click="logout">退出</van-tabbar-item>
    </van-tabbar>
    
    <!-- 添加账单弹窗 -->
    <van-dialog
      v-model:show="showAddDialog"
      title="添加账单"
      show-cancel-button
      @confirm="addBill"
    >
      <van-form ref="addForm">
        <van-field
          v-model="newBill.title"
          label="标题"
          placeholder="请输入账单标题"
          :rules="[{ required: true, message: '请输入标题' }]"
        />
        <van-field
          v-model="newBill.amount"
          label="金额"
          type="number"
          placeholder="请输入金额"
          :rules="[{ required: true, message: '请输入金额' }]"
        />
        <van-field
          v-model="newBill.category"
          label="分类"
          placeholder="请输入分类"
          :rules="[{ required: true, message: '请输入分类' }]"
        />
        <van-field
          v-model="newBill.description"
          label="描述"
          type="textarea"
          placeholder="请输入描述（可选）"
          rows="2"
        />
        <van-field
          v-model="newBill.date"
          label="日期"
          readonly
          placeholder="请选择日期"
          @click="showDatePicker = true"
        />
      </van-form>
    </van-dialog>
    
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { useAuthStore } from '../stores/auth'
import { useBillsStore } from '../stores/bills'

const router = useRouter()
const authStore = useAuthStore()
const billsStore = useBillsStore()

const activeTab = ref(0)
const searchValue = ref('')
const loading = ref(false)
const finished = ref(false)
const refreshing = ref(false)

const bills = computed(() => billsStore.bills)
const isAdmin = computed(() => authStore.isAdmin)

const showAddDialog = ref(false)
const showDatePicker = ref(false)
const newBill = ref({
  title: '',
  amount: '',
  category: '',
  description: '',
  date: new Date().toISOString().split('T')[0]
})

const onLoad = async () => {
  await billsStore.fetchBills()
  loading.value = false
  finished.value = true
}

const onRefresh = async () => {
  refreshing.value = true
  await billsStore.fetchBills()
  refreshing.value = false
}

const onSearch = () => {
  // 搜索功能可以在这里实现
  showToast('搜索功能开发中...')
}

const viewBill = (id) => {
  router.push(`/bills/${id}`)
}

const addBill = async () => {
  const result = await billsStore.createBill({
    ...newBill.value,
    amount: parseFloat(newBill.value.amount)
  })
  
  if (result.success) {
    showToast('添加成功')
    showAddDialog.value = false
    newBill.value = {
      title: '',
      amount: '',
      category: '',
      description: '',
      date: new Date().toISOString().split('T')[0]
    }
  } else {
    showToast(result.error)
  }
}

const onDateConfirm = (value) => {
  newBill.value.date = value.join('-')
  showDatePicker.value = false
}

const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

const logout = () => {
  showDialog({
    title: '确认退出',
    message: '确定要退出登录吗？',
  }).then(() => {
    authStore.logout()
    router.push('/login')
  })
}

onMounted(() => {
  billsStore.fetchBills()
})
</script>

<style scoped>
.bills-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.amount-positive {
  color: #07c160;
}

.amount-negative {
  color: #ee0a24;
}

.add-button {
  position: fixed;
  bottom: 80px;
  right: 20px;
  z-index: 100;
}
</style>
